<?php
if (!defined('CX')) {
    exit();
}

/**
 *
 *
 * @author 星期八 <ixqbar@gmail.com>
 * @editor $Author: ixqbar $
 * @date $Date: 2011-05-07 13:24:30 +0000 (Sat, 07 May 2011) $
 * @version $Revision: 3 $
 */
include_once APPLICATION_PATH . '/library/core/core.class.php';

final class CXRoute {
    private $monitor;

    private function  __construct() {
        register_shutdown_function(array('CXTool', 'halt'));
        //set_error_handler(array('CXTool', 'error'), E_ALL | E_STRICT);
        set_exception_handler(array('CXTool', 'exception'));

        $this->monitor = CXMonitor::instance();
    }

    private function  __clone() {}

    public static function instance() {
        return new self();
    }

    /**
     * request_url http://www.cx.com/index/index/id/3/
     * url index/index/id/3
     */
    public function dispatch() {
        $this->monitor->before();
        
        $_GET = array();
        $url = trim($_SERVER['REQUEST_URI'], "/");
        $this->monitor->record('request_url:' . $url);
        
        if ($url) {
            $url_parse = explode('/', $url);
            $controller_class = strtolower(array_shift($url_parse));
            $controller_method = $url_parse ? strtolower(array_shift($url_parse)) : 'index';
            if ($url_parse) {
                if (count($url_parse) % 2) {
                    array_push($url_parse, '');
                }
                $url_parse = array_chunk($url_parse, 2);
                foreach ($url_parse as $get) {
                    $_GET[$get[0]] = $get[1];
                }
            }
        } else {
            list($controller_class, $controller_method) = explode(':', CXTool::getConfig('controller'));
        }

        $controller_file = APPLICATION_CONTROLLER_PATH . '/' . $controller_class . '.controller.php';
        if (file_exists($controller_file)) {
            try {
                include_once $controller_file;
                $controller_class .= 'Controller';
                $controller_handle = new $controller_class;
                if (method_exists($controller_handle, $controller_method)) {
                    $controller_handle->$controller_method();
                } else {
                    $controller_handle->common();
                }
            }
            catch (Exception $e) {
                $this->monitor->record($e->getMessage(), 'exception');
            }
        }
        else {
            $this->monitor->record($controller_file . ' not exist', 'warn');
        }
        
        $this->monitor->after();
    }
}

?>
